package com.smartcampusbackend.controller;

import com.smartcampusbackend.model.InterestCommunity;
import com.smartcampusbackend.model.InterestCommunityMember;
import com.smartcampusbackend.model.User;
import com.smartcampusbackend.service.InterestCommunityService;
import com.smartcampusbackend.service.TokenService;
import com.smartcampusbackend.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/interest-community")
@CrossOrigin(origins = "*")
public class InterestCommunityController {

    @Autowired
    private InterestCommunityService communityService;
    
    @Autowired
    private TokenService tokenService;
    
    @Autowired
    private UserService userService;

    // 获取当前登录用户信息
    private Integer getCurrentUserId(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            String username = tokenService.getUsernameByToken(token);
            if (username != null) {
                User user = userService.getByUsername(username);
                return user != null ? user.getId() : null;
            }
        }
        return null;
    }

    // 创建兴趣社群
    @PostMapping("/create")
    public ResponseEntity<?> createCommunity(
            @RequestBody InterestCommunity community,
            HttpServletRequest request) {
        try {
            Integer userId = getCurrentUserId(request);
            if (userId == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("code", 401);
                response.put("message", "用户未登录");
                response.put("data", null);
                return ResponseEntity.status(401).body(response);
            }
            InterestCommunity created = communityService.createCommunity(community, userId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "社群创建成功");
            response.put("data", created);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("message", e.getMessage());
            response.put("data", null);
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 删除兴趣社群
    @DeleteMapping("/{communityId}")
    public ResponseEntity<?> deleteCommunity(
            @PathVariable Integer communityId,
            HttpServletRequest request) {
        try {
            Integer userId = getCurrentUserId(request);
            if (userId == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("code", 401);
                response.put("message", "用户未登录");
                response.put("data", null);
                return ResponseEntity.status(401).body(response);
            }
            String token = request.getHeader("Authorization");
            String username = null;
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
                username = tokenService.getUsernameByToken(token);
            }
            User user = userService.getByUsername(username);
            boolean isAdmin = user != null && "ADMIN".equals(user.getRole());
            boolean success = communityService.deleteCommunity(communityId, userId, isAdmin);
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "社群删除成功");
            response.put("data", null);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("message", e.getMessage());
            response.put("data", null);
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 获取所有社群
    @GetMapping("/all")
    public ResponseEntity<?> getAllCommunities() {
        try {
            List<InterestCommunity> communities = communityService.getAllCommunities();
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "获取成功");
            response.put("data", communities);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("message", e.getMessage());
            response.put("data", null);
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 根据分类获取社群
    @GetMapping("/category/{category}")
    public ResponseEntity<?> getCommunitiesByCategory(
            @PathVariable String category) {
        try {
            List<InterestCommunity> communities = communityService.getCommunitiesByCategory(category);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "获取成功");
            response.put("data", communities);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("message", e.getMessage());
            response.put("data", null);
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 加入社群
    @PostMapping("/{communityId}/join")
    public ResponseEntity<?> joinCommunity(
            @PathVariable Integer communityId,
            HttpServletRequest request) {
        try {
            Integer userId = getCurrentUserId(request);
            if (userId == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("code", 401);
                response.put("message", "用户未登录");
                response.put("data", null);
                return ResponseEntity.status(401).body(response);
            }
            boolean success = communityService.joinCommunity(communityId, userId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "成功加入社群");
            response.put("data", null);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("message", e.getMessage());
            response.put("data", null);
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 退出社群
    @PostMapping("/{communityId}/leave")
    public ResponseEntity<?> leaveCommunity(
            @PathVariable Integer communityId,
            HttpServletRequest request) {
        try {
            Integer userId = getCurrentUserId(request);
            if (userId == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("code", 401);
                response.put("message", "用户未登录");
                response.put("data", null);
                return ResponseEntity.status(401).body(response);
            }
            boolean success = communityService.leaveCommunity(communityId, userId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "成功退出社群");
            response.put("data", null);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("message", e.getMessage());
            response.put("data", null);
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 获取用户创建的社群
    @GetMapping("/my-created")
    public ResponseEntity<?> getMyCreatedCommunities(HttpServletRequest request) {
        try {
            Integer userId = getCurrentUserId(request);
            if (userId == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("code", 401);
                response.put("message", "用户未登录");
                response.put("data", null);
                return ResponseEntity.status(401).body(response);
            }
            List<InterestCommunity> communities = communityService.getUserCreatedCommunities(userId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "获取成功");
            response.put("data", communities);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("message", e.getMessage());
            response.put("data", null);
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 获取用户加入的社群
    @GetMapping("/my-joined")
    public ResponseEntity<?> getMyJoinedCommunities(HttpServletRequest request) {
        try {
            Integer userId = getCurrentUserId(request);
            if (userId == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("code", 401);
                response.put("message", "用户未登录");
                response.put("data", null);
                return ResponseEntity.status(401).body(response);
            }
            List<InterestCommunity> communities = communityService.getUserJoinedCommunities(userId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "获取成功");
            response.put("data", communities);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("message", e.getMessage());
            response.put("data", null);
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 获取社群成员
    @GetMapping("/{communityId}/members")
    public ResponseEntity<?> getCommunityMembers(
            @PathVariable Integer communityId) {
        try {
            List<InterestCommunityMember> members = communityService.getCommunityMembers(communityId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "获取成功");
            response.put("data", members);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("message", e.getMessage());
            response.put("data", null);
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 检查用户是否已加入社群
    @GetMapping("/{communityId}/is-joined")
    public ResponseEntity<?> isUserJoined(
            @PathVariable Integer communityId,
            HttpServletRequest request) {
        try {
            Integer userId = getCurrentUserId(request);
            if (userId == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("code", 401);
                response.put("message", "用户未登录");
                response.put("data", null);
                return ResponseEntity.status(401).body(response);
            }
            boolean isJoined = communityService.isUserJoined(communityId, userId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "检查成功");
            response.put("data", isJoined);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("message", e.getMessage());
            response.put("data", null);
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 删除社群成员
    @DeleteMapping("/{communityId}/member/{memberUserId}")
    public ResponseEntity<?> removeCommunityMember(
            @PathVariable Integer communityId,
            @PathVariable Integer memberUserId,
            HttpServletRequest request) {
        try {
            Integer operatorUserId = getCurrentUserId(request);
            if (operatorUserId == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("code", 401);
                response.put("message", "用户未登录");
                response.put("data", null);
                return ResponseEntity.status(401).body(response);
            }
            String token = request.getHeader("Authorization");
            String username = null;
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
                username = tokenService.getUsernameByToken(token);
            }
            User user = userService.getByUsername(username);
            boolean isAdmin = user != null && "ADMIN".equals(user.getRole());
            boolean success = communityService.removeCommunityMember(communityId, memberUserId, operatorUserId, isAdmin);
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "成员删除成功");
            response.put("data", null);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 403);
            response.put("message", e.getMessage());
            response.put("data", null);
            return ResponseEntity.status(403).body(response);
        }
    }
} 